package com.common.datasource;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;


public class MultipleDataSource extends AbstractRoutingDataSource {

    private static final ThreadLocal<DataSourceEnum> contextHolder = new InheritableThreadLocal<>();

    /**
     *  设置数据源
     * @param db
     */
    public static void setDataSource(DataSourceEnum db){
        contextHolder.set(db);
    }

    /**
     * 取得当前数据源
     * @return
     */
    public static DataSourceEnum getDataSource(){
        return contextHolder.get();
    }

    /**
     * 清除上下文数据
     */
    public static void clear(){
        contextHolder.remove();
    }

    @Override
    protected Object determineCurrentLookupKey() {
        DataSourceEnum key = getDataSource();
        if (key != null) {
            return key;
        }
        return DataSourceEnum.DB1;
    }
}
